// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.syncserver;

import com.google.appengine.syncserver.entities.SharedPreferences;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet to view data in the server.
 */
@SuppressWarnings("serial")
public class ViewServlet extends HttpServlet {
  private static final String USERNAME_PARAMETER = "user";
  private static final String FILE_PARAMETER = "file";
  private static final String NO_PARAMETER_ERROR = "%s parameter not set";

  /**
   * The query should of the format ?user=String&file=String. Where user is the username
   * and file is the preferences name.
   */
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    try {
      if (req.getParameter(USERNAME_PARAMETER) == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format(
            NO_PARAMETER_ERROR, USERNAME_PARAMETER));
          return;
      } else if (req.getParameter(FILE_PARAMETER) == null) {
        resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, String.format(
            NO_PARAMETER_ERROR, FILE_PARAMETER));
        return;
      }

      resp.getOutputStream().println(getSharedPreferencesHtml(req.getParameter(USERNAME_PARAMETER),
          req.getParameter(FILE_PARAMETER)));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Get shared preferences in the form of empty string.
   *
   * @param username
   * @param filename
   */
  public static String getSharedPreferencesHtml(String username, String filename) throws Exception {
    SharedPreferences preferences = new SharedPreferences(username, filename);
    return preferences.toHtmlString();
  }
}
